package io.youngledo.usb.storage;

import io.youngledo.usb.exception.StorageConnectionException;
import io.youngledo.usb.exception.StorageOperationException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

/// **抽象对象存储服务基类 - 提取所有实现类的公共代码**
///
/// 包含通用的连接检查、文件夹创建等逻辑
///
@Slf4j
public abstract class AbstractObjectStorageService implements ObjectStorageService {

    protected StorageConfig config;
    protected volatile boolean connected = false;

    /// **检查连接状态，如果未连接则抛出异常**
    ///
    protected final void checkConnection() {
        if (!isConnected()) {
            throw StorageConnectionException.authenticationFailed("Not connected to storage service");
        }
    }

    @Override
    public boolean isConnected() {
        return connected;
    }

    @Override
    public void disconnect() {
        this.connected = false;
        this.config = null;
        performDisconnect();
    }

    @Override
    public StorageConfig getConfig() {
        return config;
    }

    @Override
    public void createFolder(String bucketName, String folderKey) {
        checkConnection();
        if (!folderKey.endsWith("/")) {
            folderKey += "/";
        }
        uploadFile(bucketName, folderKey, new ByteArrayInputStream(new byte[0]), 0);
    }

    @Override
    public void close() {
        disconnect();
    }

    /// **子类实现具体的断开连接逻辑**
    ///
    protected abstract void performDisconnect();


    /// **提供generatePresignedUrl的默认实现**
    ///
    /// 子类可以覆盖以提供实际功能
    ///
    @Override
    public String generatePresignedUrl(String bucketName, String objectKey, int expiry) {
        throw StorageOperationException.unsupportedOperation("Presigned URL generation not supported by " + getStorageType());
    }

}